import axios from 'axios'
import Vue from 'vue'
import { getToken } from '@/utils/auth'
import FileSaver from 'file-saver'

// 默认请求链接
const uploadUrl = '/api/File/Upload'
const downloadUrl = '/api/File/Download'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  headers: {
    Authorization: getToken()
  }
})

export default {
  // 通用文件上传
  upload: (data, url = uploadUrl) => {
    return service.post(url, data)
  },
  // 通用文件下载
  download: (params, filename, url = downloadUrl) => {
    return service.post(url, params, {
      responseType: 'blob'
    }).then(res => {
      // 如果接口返回错误，则进行信息提示
      if (res.type === 'application/json') {
        const reader = new window.FileReader()
        reader.onload = function() {
          const response = JSON.parse(reader.result)
          if (response.error_message) {
            Vue.prototype.$message(response.error_message, 'error')
          }
        }
        reader.readAsText(res.data)
      }
      // 文件流处理 - 兼容safari安全策略限制blob下载
      const blob = new Blob([res.data], { type: 'application/octet-stream' })
      FileSaver.saveAs(blob, filename)
    })
  }
}
